<!-- 商品分类 -->
<template>
  <div class="product-category">
    <!-- 产品的分类 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">产品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>产品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片整体内容 -->
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="openAddDailog">添加按钮</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="categoryDatas.data"
        style="width: 100%"
        row-key="id"
        border
        :tree-props="{ children: 'children' }"
      >
        <el-table-column prop="id" label="序号" width="180"> </el-table-column>
        <el-table-column prop="title" label="标题" width="180">
        </el-table-column>
        <el-table-column prop="img" label="缩略图" width="180">
          <template slot-scope="scope">
            <img :src="Setting.baseUrl + scope.row.img" alt="" width="50" />
          </template>
        </el-table-column>

        <el-table-column prop="is_show" label="是否可用">
          <!-- 模板传递数据值可以通过scope -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_show"
              active-value="1"
              active-text="可"
              inactive-text="否"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              @click="handleDeleteClick(scope.row)"
              type="danger"
              size="small"
              >删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleEditClick(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页的数据 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="categoryDatas.count"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类的弹框 -->
    <el-dialog title="添加分类" :visible.sync="dialogAddFormVisible">
      <el-form :model="cateDatas">
        <el-form-item label="分类选择" label-width="80px">
          <el-cascader
            v-model="value"
            clearable
            ref="cascader"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="handleChangecascader(value)"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="标题" label-width="80px">
          <el-input v-model="cateDatas.title"></el-input>
        </el-form-item>
        <el-form-item label="缩略图" label-width="80px">
          <el-upload
            class="avatar-uploader"
            :action="Setting.apiBaseUrl + '/upload/img'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="Setting.baseUrl + imageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示" label-width="80px">
          <el-switch
            v-model="cateDatas.is_show"
            active-value="1"
            active-text="可"
            inactive-text="否"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddCategorySubmitForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 编辑分类的弹框 -->
    <el-dialog title="编辑分类" :visible.sync="dialogEditFormVisible">
      <el-form :model="eidtDatas">
        <el-form-item label="分类选择" label-width="80px">
          <el-cascader
            v-model="editValue"
            :options="options"
            :props="{ checkStrictly: true }"
            @change="handleChangecascader(value)"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="标题" label-width="80px">
          <el-input v-model="eidtDatas.title"></el-input>
        </el-form-item>
        <el-form-item label="缩略图" label-width="80px">
          <el-upload
            class="avatar-uploader"
            :action="Setting.apiBaseUrl + '/upload/img'"
            :show-file-list="false"
            :on-success="handleEditAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageEditUrl"
              :src="Setting.baseUrl + imageEditUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示" label-width="80px">
          <el-switch
            v-model="eidtDatas.is_show"
            active-value="1"
            active-text="可"
            inactive-text="否"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCategorySubmitForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Setting from "@/utils/setting.js";
import {
  categoryAddApi,
  categoryDeleApi,
  categoryEditApi,
} from "@/api/product.js";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      page: 1,
      size: 5,
      Setting,
      cateDatas: {
        title: "",
        is_show: "1",
        img: "",
      },
      value: [],
      currentPage: 1,
      dialogAddFormVisible: false,
      imageUrl: "",
      imageEditUrl: "",
      dialogEditFormVisible: false,
      eidtDatas: { title: "", is_show: "1", img: "" },
      editValue: [],
    };
  },
  //计算属性 类似于data概念
  computed: {
    categoryDatas() {
      return this.$store.state.product.categoryListDatas;
    },
    options() {
      console.log(this.$store.state.product.AddCategoryListDatas);
      return this.$store.state.product.AddCategoryListDatas;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getCategoryListDatas() {
      this.$store.dispatch("actChangeCategoryListDatas", {
        page: this.page,
        size: this.size,
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.getCategoryListDatas();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.getCategoryListDatas();
    },
    getAddCategoryListDatas() {
      this.$store.dispatch("actAddChangeCategoryListDatas");
    },
    //打开添加的对画框
    openAddDailog() {
      this.dialogAddFormVisible = true;
      // 更新分类数据
      this.getAddCategoryListDatas();
    },
    // 添加中的图片的内容
    handleAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data.name;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 修改级联数据
    handleChangecascader(value) {
      console.log(value);
      this.value = value;
      //  cateDatas: {
      //   title: "",
      //   is_show: "1",
      //   img: "",
      // },
    },
    // 添加的提交
    AddCategorySubmitForm() {
      this.$set(this.cateDatas, "img", this.imageUrl);
      this.$set(this.cateDatas, "pid", this.value.pop());
      console.log(this.cateDatas);
      // 提交
      categoryAddApi(this.cateDatas).then((rel) => {
        this.getCategoryListDatas();
        this.dialogAddFormVisible = false;
        // 清空添加的数据
        this.cateDatas = { title: "", is_show: "1", img: "" };
        this.imageUrl = "";
        alert(rel.data.msg);
      });
    },
    // 删除事件
    handleDeleteClick(rowData) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(rowData);
          // 发送数据请求的过程
          categoryDeleApi(rowData).then((res) => {
            if (res.data.status == 200) {
              // 消息的提示
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              // 重新调用页面数据更新
              this.getCategoryListDatas();
            } else {
              this.$message(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 弹出编辑框
    handleEditClick(rowData) {
      // 先清空级联的值
      this.getAddCategoryListDatas();
      // 再修改
      this.dialogEditFormVisible = true;
      // 设置图片
      this.imageEditUrl = rowData.img;
      this.eidtDatas = rowData;
    },
    // 修改中的图片的内容
    handleEditAvatarSuccess(res, file) {
      console.log(res);
      console.log(file);
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageEditUrl = res.data.name;
    },
    // 修改提交
    editCategorySubmitForm() {
      this.$set(this.eidtDatas, "img", this.imageEditUrl);
      this.$set(this.eidtDatas, "pid", this.editValue.pop());
      console.log(this.eidtDatas.is_show);
      if (this.eidtDatas.is_show == false) {
        this.eidtDatas.is_show = 0;
      }
      // 提交
      categoryEditApi(this.eidtDatas).then((res) => {
        // 重新请求下list更新的数据
        this.getCategoryListDatas();
        this.dialogEditFormVisible = false;
        this.$message(res.data.msg);
      });
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getCategoryListDatas();
    this.getAddCategoryListDatas();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
</style>